<template>
	<view class="page-session">
		<cl-topbar :title="customerName" :description="status" @tap="toDetail">
			<!-- #ifndef MP -->
			<view slot="append" class="cl-topbar__icon" @tap="toDetail">
				<text class="iconfont icon-more"></text>
			</view>
			<!-- #endif -->
		</cl-topbar>

		<view class="message-list">
			<scroll-view scroll-y :scroll-top="op.scrollTop" scroll-with-animation class="scroller">
				<chat-message :list="list" :uid="uid" :intime="intime" :myName="myName" :myImg="myImg"></chat-message>
			</scroll-view>
		</view>

		<view class="opbar">
			<view class="main">
				<!-- <view class="icon">
					<text
						class="iconfont icon-microphone"
						@tap="showMicrophone"
						v-if="!op.isMicrophone"
					></text>
					<text class="iconfont icon-keyboard" @tap="hideMicrophone" v-else></text>
				</view>
 -->
				<view class="input">
					<cl-button fill round v-if="op.isMicrophone">按住说话</cl-button>
					<cl-input fill v-else @focus="onFocus" @confirm="confirm" ref="input"></cl-input>
				</view>


				
				<view class="icon">
					<text class="iconfont icon-chat" @click="confirm"></text>
				</view>
				
				<view class="icon">
					<text
						class="iconfont icon-add-circle"
						@tap="showTools"
						v-if="!op.isTools"
					></text>
					<text class="iconfont icon-subtract-circle" @tap="hideTools" v-else></text>
				</view>

				<view class="icon">
					<text class="iconfont icon-emoji" @tap="showEmoji" v-if="!op.isEmoji"></text>
					<text class="iconfont icon-keyboard" @tap="hideEmoji" v-else></text>
				</view>
			</view>

			<view class="append">
				<chat-tools :visible="op.isTools" @sendPhoto="sendPhoto"></chat-tools>
				<chat-emoji :visible="op.isEmoji" @clickEmoji="clickEmoji" ></chat-emoji>
			</view>
		</view>
		
	</view>
</template>


<script>
import ChatTools from '@/components/chat/tools';
import ChatMessage from '@/components/chat/message';
import ChatEmoji from '@/components/chat/emoji';
import http from '@/common/requestConfig.js';
//import signalR from '@microsoft/signalr';
var Hub = require('@/components/SignalRClient.js');
export default {
	components: {
		ChatTools,
		ChatMessage,
		ChatEmoji,
		http
	},

	data() {
		return {
			list: [
				
			],
			op: {
				isMicrophone: false,
				isEmoji: false,
				isTools: false,
				scrollTop: 0
			},
			access_token:"",
			customerName:"加载中...",
			status:"状态",
			uid:"0",
			intime:null,
			myName:"",
			myImg:"",
			maxUploadByte:0,
			hub:null,
			indexLocation:-1,
			isSendDetail:false,
			detailInfo:""
		};
	},
	onLoad(options) {
			//console.log($http);
			this.InitToken();
			
			let that = this;
			if(options.c){
				that.isSendDetail = true;
				that.detailInfo = options.c;
			}
			//this.scrollToBottom();
	},
	onPullDownRefresh(){
		this.GetChatRecord();
		setTimeout(function(){
			 uni.stopPullDownRefresh();
		},1000)
	},
	methods: {
		//初始化token信息
		InitToken(){
			let that = this;
			let httpData = {
				token: global.token()
			};
			http.post("user/CreateUser", httpData
			).then(res => {
				//console.log(res);
				uni.setStorageSync("token",res.message);
				that.access_token = res.data;
				//开始连接
				that.InitSignalR();
			}).catch(res=>{
				setTimeout(function(){
					that.InitToken();
				},2000)
			});
		},
		InitSignalR(){
			let that = this;
			let hub  = new Hub.HubConnection();
			that.hub = hub;
			hub.start(global.baseUrl+"/chatHub",{
			    access_token:that.access_token
			});
			
			hub.onOpen = (res)=>{
			    console.log("连接已开启")
				hub.invoke("ClientGetBaseInfo").then((res)=>{
				    res = JSON.parse(res);
					that.customerName = res.customerName;
					that.status = res.customerStatus;
					that.uid = res.uid;
					that.intime = res.intime;
					that.myName = res.myName;
					that.myImg = res.myImg;
					that.maxUploadByte = res.maxUploadByte;
				});
				
				that.list=[];
				that.GetChatRecord(true);
				
				if(that.isSendDetail){
					that.hub.invoke("ClientSendMessage",1,that.detailInfo).then((res)=>{
						let data =  {
							avatarUrl:
								global.baseUrl + that.myImg,
							content: res,
							my: true,
							type: 'text',
							nickName: that.myName
						};
						that.list.push(data);
						that.scrollToBottom();
					});
				}
				
				
				//监听新信息
				hub.on("ClientOnMessage",(res)=>{
				    res.avatarUrl = global.baseUrl + res.avatarUrl;
					if(res.type == "image") res.imageUrl=global.baseUrl + res.imageUrl;
					setTimeout(function(){
						that.list.push(res);
						that.scrollToBottom();
					},200);
				})
				//that.chatImgProcess();
				//that.list = contentresult;
			};
			
			//连接关闭事件
			hub.onClose = (res)=>{
			    console.log("连接意外关闭");
				that.InitToken();
			};
			
			//通讯过程中的Error事件
			hub.onError = (res) =>{
			    console.log(res)
			};
		},
		GetChatRecord(isBottom=false){
			let that = this;
				that.hub.invoke("ClientGetChatRecord",that.indexLocation).then((res)=>{
				    res = JSON.parse(res);
					//console.log(res);
					if(that.indexLocation==0) return;
					that.indexLocation = res.indexLocation;
					res.list.forEach(function(item,index,arr){
						arr[index].avatarUrl = global.baseUrl + arr[index].avatarUrl;
						if(arr[index].type == "image")
					    arr[index].imageUrl = global.baseUrl + arr[index].imageUrl;
					})
					that.list = res.list.concat(that.list);
					if(isBottom){
						that.scrollToBottom();
					}
					//that.list = res.list + that.list;
				});
		},
		//聊天文字信息表情包处理
		chatImgProcess(){
			let that = this;
			const regex = new RegExp('<img', 'gi');
			that.list.forEach(function(item,index,arr){
				//console.log(arr[index].content);
				if(arr[index].content)
			   arr[index].content = arr[index].content.replace(regex, `<img style="width: 17px;height:17px;vertical-align: sub;"`);
			})
		},
		showMicrophone() {
			this.op.isMicrophone = true;
			this.hideTools();
			this.hideEmoji();
			this.scrollToBottom();
		},
		hideMicrophone() {
			this.op.isMicrophone = false;
		},
		showEmoji() {
			this.op.isEmoji = true;
			this.hideTools();
			this.hideMicrophone();
			this.scrollToBottom();
		},
		hideEmoji() {
			this.op.isEmoji = false;
		},
		showTools() {
			this.op.isTools = true;
			this.hideEmoji();
			this.hideMicrophone();
			this.scrollToBottom();
		},
		hideTools() {
			this.op.isTools = false;
		},
		scrollToBottom() {
			setTimeout(() => {
				this.op.scrollTop = 1000000 + Math.random();
			}, 300);
		},
		onFocus() {
			this.hideEmoji();
			this.hideTools();
			this.hideMicrophone();
			this.scrollToBottom();
		},

		toBack() {
			//uni.navigateBack();
			window.history.back();
		},
		toDetail() {
			uni.navigateTo({
				url: '/pages/chat/detail'
			});
		},
		clickEmoji(item){
			let that = this;
			//console.log('click em',item);
			// if(!this.$refs.input.value2)this.$refs.input.value2 ="";
			// this.$refs.input.value2 += "<img src='"+item+"' />";
			that.hub.invoke("ClientSendMessage",2,item).then((res)=>{
			    //res = JSON.parse(res);
				//console.log(res);
				let data =  {
					avatarUrl:
						global.baseUrl + that.myImg,
					content: res,
					my: true,
					type: 'text',
					nickName: that.myName
				};
				
				that.list.push(data);
				that.scrollToBottom();
			});
		},
		sendPhoto(){
			let that = this;
			http.urlImgUpload('user/uploadphoto',{
			    name:"file", //默认 file
			    count:1,//默认 9
			    sizeType:['original', 'compressed'],//默认 ['original', 'compressed']
			    sourceType:['album','camera'],//默认 ['album','camera']
			    data:{}, //可不填,
			    isPrompt: true,//（默认 true 说明：本接口抛出的错误是否提示）
			    load: true,//（默认 true 说明：本接口是否提示加载动画）
			    // header: { //默认 无 说明：请求头
			    //     'Content-Type': 'application/json'
			    // },
			    isFactory: true, //（默认 true 说明：本接口是否调用公共的数据处理方法，设置false后isPrompt参数奖失去作用）
			    maxSize: that.maxUploadByte, //（默认 无 说明：上传的文件最大字节数限制，默认不限制）
			    onEachUpdate: res => {
			        //console.log("单张上传成功返回：",res);
			    },
			    onProgressUpdate: res => {
			        //console.log("上传进度返回：",res);
			    }
			}).then(res => {
			    //console.log("全部上传完返回结果：",res);
				that.hub.invoke("ClientSendMessage",3,res.data).then((res2)=>{
					let data =  {
						avatarUrl:
							global.baseUrl + that.myImg,
						imageUrl:global.baseUrl + res2,
						my: true,
						type: 'image',
						nickName: that.myName
					};
					that.list.push(data);
					that.scrollToBottom();
				});
			});
		},
		confirm(item){
			let that = this;
			if(!this.$refs.input.value2 || this.$refs.input.value2 == ""){
				uni.showModal({
					title:"系统提示",
					showCancel:false,
					content:"消息内容不能为空"
				});
				return;
			}
			that.hub.invoke("ClientSendMessage",1,this.$refs.input.value2).then((res)=>{
				that.$refs.input.value2 = "";
				let data =  {
					avatarUrl:
						global.baseUrl + that.myImg,
					content: res,
					my: true,
					type: 'text',
					nickName: that.myName
				};
				that.list.push(data);
				that.scrollToBottom();
			});
		}
	}
};
</script>

<style lang="scss">
page {
	height: 100%;
	overflow: hidden;
}

.page-session {
	display: flex;
	flex-direction: column;
	height: 100%;
	padding-bottom: env(safe-area-inset-bottom);
	box-sizing: border-box;

	.message-list {
		// height: calc(100% - 100rpx);
		flex: 1;
		overflow: hidden;

		.scroller {
			height: 100%;
		}
	}

	.opbar {
		flex-shrink: 0;
		z-index: 9;
		background-color: #fff;
		border-top: 1rpx solid #f7f7f7;

		.main {
			display: flex;
			align-items: center;
			height: 100rpx;

			.icon {
				height: 80rpx;
				width: 80rpx;
				line-height: 80rpx;
				text-align: center;
				flex-shrink: 0;

				.iconfont {
					font-size: 60rpx;
				}
			}

			.input {
				flex: 1;
				margin: 0 10rpx;
			}
		}
	}
}
</style>
